<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2018 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 老猫 <thinkcmf@126.com>
// +----------------------------------------------------------------------
namespace app\portal\controller;

use app\portal\model\Article;
use app\portal\model\PortalCategoryModel;
use app\portal\model\PortalPostModel;
use app\portal\model\UserModel as AppUserModel;
use cmf\controller\AdminBaseController;
use think\Db;
use think\Request;

class AdminArticleController extends AdminBaseController
{
    /**
     * 文章列表
     * @adminMenu(
     *     'name'   => '文章管理',
     *     'parent' => 'portal/AdminIndex/default',
     *     'display'=> true,
     *     'hasView'=> true,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '文章列表',
     *     'param'  => ''
     * )
     */
    public function index()
    {
        $content = hook_one('portal_admin_article_index_view');

        if (!empty($content))
        {
            return $content;
        }

        $param = $this->request->param();

        $categoryId = $this->request->param('category', 0, 'intval');

        $Article = new Article();
        $data = $Article->adminArticleList($param);

        $data->appends($param);

        $portalCategoryModel = new PortalCategoryModel();
        $categoryTree = $portalCategoryModel->adminCategoryTree($categoryId);

        $this->assign('start_time', isset($param['start_time']) ? $param['start_time'] : '');
        $this->assign('end_time', isset($param['end_time']) ? $param['end_time'] : '');
        $this->assign('keyword', isset($param['keyword']) ? $param['keyword'] : '');

        $this->assign('articles', $data->items());
        $this->assign('category_tree', $categoryTree);
        $this->assign('category', $categoryId);
        $this->assign('page', $data->render());

        return $this->fetch();
    }

    // 添加文章
    public function add(Request $request)
    {
        if ($request->isPost())
        {
            $param = $this->request->param(); // 获取提交的数据

            if ($param['pic'] === '' && $param['video'] === '')
            {
                $this->success('视频或图片不能为空!');
            }

            $validate = $this->validate($param, '\app\portal\validate\Article'); //校检数据是否正确
            if (true === $validate)
            {
                if (true === $this->addArt($param))
                { // 执行数据添加
                    $this->success('添加成功!');
                }
            }
            else
            {
                $this->error($validate);
            }
        }
        $id = $this->request->param('id', 0, 'intval');
        $user = new AppUserModel();
        $post = $user->where('id', session('PORTRL_ID'))->find();
        $postCategories = $post->categories()->alias('a')->column('a.name', 'a.id');
        $postCategoryIds = implode(',', array_keys($postCategories));
        $this->assign('post_categories', $postCategories);
        $this->assign('post_category_ids', $postCategoryIds);
        return $this->fetch('edit');
    }

    /**
     * 编辑文章
     * @adminMenu(
     *     'name'   => '编辑文章',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> true,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '编辑文章',
     *     'param'  => ''
     * )
     */
    public function edit()
    {
        $content = hook_one('portal_admin_article_edit_view');

        if (!empty($content))
        {
            return $content;
        }

        $id = $this->request->param('id', 0, 'intval');
        $article = new Article();
        $post = $article->where('id', $id)->find(); //$portalPostModel->where('id', $id)->find();

        if ($this->request->isPost())
        {
            $param = $this->request->param(); // 获取提交的数据

            if ($param['pic'] === '' && $param['video'] === '')
            {
                $this->success('视频或图片不能为空!');
            }

            $validate = $this->validate($param, '\app\portal\validate\Article'); //校检数据是否正确
            if (true === $validate)
            {
                if (true === $this->addArt($param, ['id', $param['id']]))
                { // 执行数据添加
                    $this->success('修改成功!');
                }
            }
            else
            {
                $this->error($validate);
            }

        }

        if (null == $post)
        {
            $this->error('文章不存在!');
        }
        $postCategories = $post->categories()->alias('a')->column('a.name', 'a.id');
        $postCategoryIds = implode(',', array_keys($postCategories));

        // $themeModel = new ThemeModel();
        // $articleThemeFiles = $themeModel->getActionThemeFiles('portal/Article/index');
        // $this->assign('article_theme_files', $articleThemeFiles);
        $this->assign('post', $post);
        $this->assign('post_categories', $postCategories);
        $this->assign('post_category_ids', $postCategoryIds);

        return $this->fetch();
    }

    /**
     * 文章删除
     * @adminMenu(
     *     'name'   => '文章删除',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> false,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '文章删除',
     *     'param'  => ''
     * )
     */
    public function delete()
    {
        $param = $this->request->param();
        if (isset($param['id']))
        {
            $id = $this->request->param('id', 0, 'intval');
            $article = new Article();
            $article->where('id', $param['id'])->update(['status' => 0]);
            $this->success("删除成功！", '');
        }

        if (isset($param['ids']))
        {
            $ids = $this->request->param('ids/a');
            $data = [];
            foreach ($ids as $key => $val)
            {
                $data[$key]['status'] = 0;
                $data[$key]['id'] = $val;
            }
            $article = new Article();
            if ($article->saveAll($data))
            {
                $this->success("删除成功！", '');
            }
        }
    }

    /**
     * 文章发布
     * @adminMenu(
     *     'name'   => '文章发布',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> false,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '文章发布',
     *     'param'  => ''
     * )
     */
    public function publish()
    {
        $param = $this->request->param();
        $portalPostModel = new PortalPostModel();

        if (isset($param['ids']) && isset($param["yes"]))
        {
            $ids = $this->request->param('ids/a');

            $portalPostModel->where(['id' => ['in', $ids]])->update(['post_status' => 1, 'published_time' => time()]);

            $this->success("发布成功！", '');
        }

        if (isset($param['ids']) && isset($param["no"]))
        {
            $ids = $this->request->param('ids/a');

            $portalPostModel->where(['id' => ['in', $ids]])->update(['post_status' => 0]);

            $this->success("取消发布成功！", '');
        }
    }

    /**
     * 文章置顶
     * @adminMenu(
     *     'name'   => '文章置顶',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> false,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '文章置顶',
     *     'param'  => ''
     * )
     */
    public function top()
    {
        $param = $this->request->param();
        $portalPostModel = new PortalPostModel();

        if (isset($param['ids']) && isset($param["yes"]))
        {
            $ids = $this->request->param('ids/a');

            $portalPostModel->where(['id' => ['in', $ids]])->update(['is_top' => 1]);

            $this->success("置顶成功！", '');
        }

        if (isset($_POST['ids']) && isset($param["no"]))
        {
            $ids = $this->request->param('ids/a');

            $portalPostModel->where(['id' => ['in', $ids]])->update(['is_top' => 0]);

            $this->success("取消置顶成功！", '');
        }
    }

    /**
     * 文章推荐
     * @adminMenu(
     *     'name'   => '文章推荐',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> false,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '文章推荐',
     *     'param'  => ''
     * )
     */
    public function recommend()
    {
        $param = $this->request->param();
        $portalPostModel = new PortalPostModel();

        if (isset($param['ids']) && isset($param["yes"]))
        {
            $ids = $this->request->param('ids/a');

            $portalPostModel->where(['id' => ['in', $ids]])->update(['recommended' => 1]);

            $this->success("推荐成功！", '');
        }
        if (isset($param['ids']) && isset($param["no"]))
        {
            $ids = $this->request->param('ids/a');

            $portalPostModel->where(['id' => ['in', $ids]])->update(['recommended' => 0]);

            $this->success("取消推荐成功！", '');
        }
    }

    /**
     * 文章排序
     * @adminMenu(
     *     'name'   => '文章排序',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> false,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '文章排序',
     *     'param'  => ''
     * )
     */
    public function listOrder()
    {
        parent::listOrders(Db::name('portal_category_post'));
        $this->success("排序更新成功！", '');
    }

    public function move()
    {
    }

    public function copy()
    {
    }

    /**
     * 文章添加
     * @param array 数据
     */
    private function addArt($data, $where = [])
    {
        try {
            $data['create_time'] = strtotime($data['create_time']);
            $article = new Article();
            $data['type'] = $data['video'] ? 2 : 1; // 设置 视频类型文章 or 普通文章类型
            $user_id = session('PORTRL_ID');
            $data['author'] = Db::name('user')->where('id', $user_id)->field('user_login')->find()['user_login'];
            $result = $article->allowField(true)->save($data, $where);
            if (!empty($result))
            {
                return true;
            }
            return $this->error($article->getError());
        }
        catch (\Exception $e)
        {
            $this->error($e->getMessage());
        }
    }
}
